<template>
  <div
    ref="trainMapBox"
    v-loading="!showMap"
    class="train-map"
    @mousewheel.prevent.stop="mapWheel"
    @mousedown.prevent.stop="mapDown"
    @mousemove.prevent.stop="mapMove"
  >
    <img
      ref="trainMap"
      class="train-map-img"
      src="@/assets/dashboard/qingzang-train-map.jpg"
      @load="mapLoad"
    >
  </div>
</template>

<script>
// databackPlay.png
// qingzang-train-map.jpg
export default {
  data() {
    return {
      showMap: false,
      imgStyle: {
        canMove: false,
        translateX: 0,
        translateY: 0,
        scale: 1,
        minScale: 1
      }
    }
  },
  mounted() {
    const that = this
    setTimeout(function() {
      that.showMap = true
    }, 1)
  },
  beforeDestroy() {},
  methods: {
    mapLoad(ev) {
      this.showMap = true
      const boxWidth = this.$refs.trainMapBox.clientWidth
      const boxHeight = this.$refs.trainMapBox.clientHeight
      const imgWidth = this.$refs.trainMap.naturalWidth
      const imgHeight = this.$refs.trainMap.naturalHeight

      this.imgStyle.translateX = (boxWidth - imgWidth) / 2
      this.imgStyle.translateY = (boxHeight - imgHeight) / 2
      const scalex = boxWidth / imgWidth
      const scaley = boxHeight / imgHeight
      this.imgStyle.scale = scalex < scaley ? scaley : scalex
      this.imgStyle.minScale = this.imgStyle.scale

      this.$refs.trainMap.style.transform = `translate(${
        this.imgStyle.translateX
      }px,${this.imgStyle.translateY}px) scale(${this.imgStyle.scale})`
    },
    mapWheel(ev) {
      const delta = ev.wheelDeltaY > 0 ? 0.01 : -0.01
      const scale = this.imgStyle.scale + delta

      if (scale > this.imgStyle.minScale) {
        this.imgStyle.scale = scale
      }

      this.$refs.trainMap.style.transform = `translate(${
        this.imgStyle.translateX
      }px,${this.imgStyle.translateY}px) scale(${this.imgStyle.scale})`
    },
    mapDown(ev) {
      this.imgStyle.canMove = true
      this.imgStyle.startPoint = {
        x: ev.pageX,
        y: ev.pageY
      }
      document.body.addEventListener('mouseup', this.mapUp)
    },
    mapUp(ev) {
      this.imgStyle.canMove = false
      document.body.removeEventListener('mouseup', this.mapUp)
    },
    mapMove(ev) {
      if (this.imgStyle.canMove) {
        const pageX = ev.pageX
        const pageY = ev.pageY
        const deltaX = pageX - this.imgStyle.startPoint.x
        const deltaY = pageY - this.imgStyle.startPoint.y
        this.imgStyle.translateX += deltaX
        this.imgStyle.translateY += deltaY

        this.$refs.trainMap.style.transform = `translate(${
          this.imgStyle.translateX
        }px,${this.imgStyle.translateY}px) scale(${
          this.imgStyle.scale
        })`

        this.imgStyle.startPoint = {
          x: pageX,
          y: pageY
        }
      }
    }
  }
}
</script>
